package org.jiucheng.magpiebridge.transfer.aio;

import java.nio.ByteBuffer;
import java.nio.channels.CompletionHandler;

import org.jiucheng.magpiebridge.client.aio.ClientAttachment;
import org.jiucheng.magpiebridge.protocol.Message;
import org.jiucheng.magpiebridge.util.Cfg;

/**
 * 
 * @author jiucheng
 *
 */
public class TransferEstablishmentCompletionHandler implements CompletionHandler<Void, TransferAttachment> {

	public void completed(Void result, TransferAttachment attachment) {
		Message message = new Message();
        message.setMagic(Message.MAGIC);
        message.setType(Message.Type.CONNECT);
        message.setUri(attachment.getUri());
        byte[] data = Cfg.getClientKey().getBytes();
        message.setData(data);
        message.setSize(data.length);
        ByteBuffer buffer = Message.toByteBuffer(message);
        if (attachment.canWrited()) {
            attachment.getClient().write(buffer, attachment.setWriteByteBuffer(buffer), new TransferConnectedCompletionHandler());
        }
	}

	public void failed(Throwable exc, TransferAttachment attachment) {
		ClientAttachment clientAttachment = attachment.getClientAttachment();
		if (clientAttachment != null) {
			clientAttachment.disconnect(attachment.getUri());
		}
		attachment.close();
	}
}
